package cn.pn.project.controller;

import cn.pn.project.client.user.UserFeign;
import cn.pn.project.common.*;
import cn.pn.project.pojo.user.User;
import cn.pn.project.tonken.utils.TokenUtil;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

@RestController
@RequestMapping("user")
public class UserController {
    //订单根据用户id 和订单状态查询
    //优惠券根据用户id 和优惠卷id查询
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserFeign userFeign;
    @Autowired
    private RedisUtils redisUtils;


    /**
     * 获取用户信息
     *
     * @return
     */
    @PostMapping("/v/findUserInfo")
    public Object findUserInfo(HttpServletRequest request)  throws Exception{
        String token=request.getHeader("token");
        if (token == null||token.length()==0) //不能传入null 的userId
            return DtoUtil.returnSuccess("没有用户凭证","1009");
        try {
            return DtoUtil.returnSuccess("获取成功",(User)redisUtils.get(token));
        }catch (Exception e){
            System.out.println(token);
            return DtoUtil.returnFail("用户未登录","0001");
        }

    }

    /**
     * 修改密码
     *
     * @param oidPwd 用户原密码
     * @param newPwd 用户新密码
     * @return
     */
    @PostMapping("/v/changePwd")
    public Object changePwd(String oidPwd, String newPwd, String newPwd2,HttpServletRequest request)  throws Exception{
        if ( oidPwd == null || newPwd == null || newPwd2 == null) //不能传入null 的userId
            return DtoUtil.returnSuccess("参数缺失","1011");
        if (oidPwd.length() < 6 || newPwd.length() < 6 || newPwd2.length() < 6)
            return DtoUtil.returnSuccess("请输入六位数以上的密码","1013");
        if (!newPwd.equals(newPwd2))
            return DtoUtil.returnSuccess("两次输入密码不一样","1014");
        String token=request.getHeader("token");
        User u = null;//(User) redisUtils.get(token);
        try {
            u= (User)redisUtils.get(token);
        }catch (Exception e){
            System.out.println(token);
            return DtoUtil.returnSuccess("用户未登录","0001");
        }
        String a=QueryUtil.MD5(oidPwd);
        if (u.getUserPwd().equals(a)) {
            u.setUserPwd(QueryUtil.MD5(newPwd));
            if (userFeign.updateUser(u)) {
                u=userFeign.findUserById(u.getUserId());
                redisUtils.update(token,u);//更新redis中的数据
                return DtoUtil.returnSuccess("修改成功");
            } else {
                return DtoUtil.returnFail("系统异常", "0002");
            }
        }
        return DtoUtil.returnSuccess("原密码不正确");
    }

    /**
     * 根据手机号码加密码登陆  1
     *
     * @param user 手机号 密码
     * @return 返回boolean值
     */
    @PostMapping("/p/login")
    public Object login(User user) throws Exception {
        if ((user.getTelephone() == null && !CommunicationNumberVerification.isMobileNO(user.getTelephone())) || (user.getUserPwd() == null && user.getUserPwd().length() < 6)) {
            return DtoUtil.returnSuccess("未填写手机号和密码","1007");
        }
        //加密
        user.setUserPwd(QueryUtil.MD5(user.getUserPwd()));
        //获取用户
        User u = userFeign.findByPhoneAndPassword(user);
        if (u == null || u.getUserId() == null || u.getUserId().equals(0))
            return DtoUtil.returnSuccess("手机号和密码错误","1008");
        //生成token
        String token = TokenUtil.getMD5Token("cn.pn.com")+"__"+TokenUtil.getMD5Token(user)+(new Date().getTime());
        //添加到redis
        //ValueOperations<String, User> users = redisTemplate.opsForValue();
        //users.set(token, u, 30, TimeUnit.MINUTES);
        redisUtils.set(token,60*30,u);
        userFeign.updateLoginTimeByUserId(u.getUserId());
        return DtoUtil.returnSuccess("登陆成功", JSON.parse("{\"data\":\"" + u + "\",\"token\":\"" + token + "\"}"));


    }

    /**
     * 退出登陆
     * @return
     * @throws Exception
     */
    @PostMapping("/v/logout")
    public Object logout(HttpServletRequest request)  throws Exception{
        String token=request.getHeader("token");
        if (token == null||token.length()==0) //不能传入null 的userId
            return DtoUtil.returnSuccess("用户未登录","0001");
        redisUtils.delete(token);
        return DtoUtil.returnSuccess("退出成功");
    }

    /**
     * 注册
     *
     * @param phone 手机号
     * @param YZM   验证码
     * @param pwd   密码
     * @return
     */
    @PostMapping("/p/register")
    public Object register(String phone, String YZM, String pwd)  throws Exception{
        if (phone == null || !CommunicationNumberVerification.isMobileNO(phone))
            return DtoUtil.returnSuccess("请填写正确的手机号");
        if (YZM == null || YZM.length() == 0)
            return DtoUtil.returnSuccess("请填写正确的验证码");
        if (pwd == null || pwd.length() < 6 || pwd.length() > 20)
            return DtoUtil.returnSuccess("请填写六位以上,20位以下的密码");
        String key = "register_YZM_" + phone;
        //手机号验证码
        ValueOperations<String, String> operations = redisTemplate.opsForValue();
        if (!redisTemplate.hasKey(key))//不存在
            return DtoUtil.returnSuccess("请先获取验证码");
        //获取rides中的验证码
        String value = (String) redisUtils.get(key);
        if (!value.equals(YZM))
            return DtoUtil.returnSuccess("请填写正确的验证码");
        //添加用户
        User u = new User();
        u.setTelephone(phone);
        u.setUserPwd(pwd);//密码
        u.setHeadImgURL("");//默认头像路径
        u.setNickName(phone);//昵称
        u.setSignature("这个人很懒，什么也没留下。。");
        u.setUserIdentity("个人");
        u.setStatus(1);
        boolean result = userFeign.insertUser(u);
        //返回执行结果
        return result ? DtoUtil.returnSuccess("注册成功") : DtoUtil.returnFail("系统异常", "0000");
    }

    /**
     * 快速登陆
     *
     * @param phone 手机号
     * @param YZM   验证码
     * @return
     */
    @PostMapping("/p/fastLogin")
    public Object fastLogin(String phone, String YZM, HttpServletResponse httpServletResponse) throws Exception {
        if (phone==null||!CommunicationNumberVerification.isMobileNO(phone))
            return "{\"success\":\"true\",\"errorCode\":\"1003\",\"msg\":\"请输入正确的手机号\",\"data\":\" \"}";
        String key = "fastLogin_YZM_" + phone;
        //ValueOperations<String, String> operations = redisTemplate.opsForValue();
        //ValueOperations<String, User> users = redisTemplate.opsForValue();
        if (redisUtils.exist(key)) {//存在
            String value = (String) redisUtils.get(key);
            if (value != null && value.equals(YZM)) {
                //删除缓存中的验证嘛
                redisTemplate.delete(key);
                //获取用户
                User user = userFeign.findByTelephone(phone);
                if (user == null) {//是否存在这个用户
                    User u = new User();
                    u.setTelephone(phone);
                    u.setUserPwd("123456");//密码
                    u.setHeadImgURL("");//默认头像路径
                    u.setNickName(phone);//昵称
                    u.setSignature("这个人很懒，什么也没留下。。");
                    u.setUserIdentity("个人");
                    u.setStatus(1);
                    userFeign.insertUser(u);
                    user = userFeign.findByTelephone(phone);
                }
                //生成token
                String token = TokenUtil.getMD5Token("cn.pn.com")+"__"+TokenUtil.getMD5Token(user)+(new Date().getTime());
                Cookie cookie=new Cookie("token", token);
                cookie.setPath("/");
                httpServletResponse.addCookie(cookie);
                //添加到redis
                redisUtils.set(token,60*30,user);//users.set(token, user, 30, TimeUnit.MINUTES);
                userFeign.updateLoginTimeByUserId(user.getUserId());
                //返回token
                return DtoUtil.returnSuccess("登陆成功", JSON.parse("{\"data\":\"" + user + "\",\"token\":\"" + token + "\"}"));
            } else {
                return DtoUtil.returnSuccess("请填写正确的验证码","1005");
            }
        } else {//不存在
            return DtoUtil.returnSuccess("请先获取验证码","1006");
        }
    }

    /**
     * 发送验证码
     *
     * @param phone 手机号
     * @return
     */
    @PostMapping("/p/sendMessage")
    public Object sendMessage(String phone, Boolean isRegister) throws Exception {
        if (phone==null||!CommunicationNumberVerification.isMobileNO(phone))
            return DtoUtil.returnSuccess("请输入正确的手机号","1003");
        String key = "";
        if (isRegister)//是注册
        {
            User u = userFeign.findByTelephone(phone);
            if (u != null && u.getUserId() != null)
                return DtoUtil.returnSuccess("此手机号已经注册过了","1004");
            key = "register_YZM_" + phone;
        } else {
            key = "fastLogin_YZM_" + phone;
        }
        //发送验证后将验证码和手机号存入rides中

       // ValueOperations<String, String> operations = redisTemplate.opsForValue();
        if (redisUtils.exist(key)) {//存在
            //获取剩余的存在时间
            Long time = redisUtils.getExpire(key);
            //返回过期时间
            return DtoUtil.returnSuccess("获取验证码过于频繁","1001",time);
        } else {//不存在
            //发送验证码
            String value = "123456";//GetMessage.getResult(phone);
            if (value == null)
                return DtoUtil.returnSuccess("短时间内发送次数过多","1002");

            //添加入缓存
            redisUtils.set(key,60*1,value);//operations.set(key, value, 1, TimeUnit.MINUTES);
            //返回时间
            return DtoUtil.returnSuccess("获取验证码成功");

        }
    }

    /**
     * 修改用户基础信息 头像路径 昵称 个性签名
     *
     * @param user
     * @param request
     * @return
     */
    @PostMapping("/v/changeBaseUserInfo")
    public Object changeBaseUserInfo(User user, HttpServletRequest request) throws Exception {
        if (user == null)
            return "{\"success\":\"false\",\"errorCode\":\"0000\",\"msg\":\"数据缺失\",\"data\":\" \"}";
        if (user.getUserId() == null || user.getUserId().equals(0))
            return "{\"success\":\"false\",\"errorCode\":\"0000\",\"msg\":\"userId参数缺失\",\"data\":\" \"}";
        if (user.getHeadImgURL() == null || user.getHeadImgURL().length() == 0)
            return "{\"success\":\"false\",\"errorCode\":\"0000\",\"msg\":\"headImgUrl参数缺失\",\"data\":\" \"}";
        if (user.getNickName() == null || user.getNickName().length() == 0)
            return "{\"success\":\"false\",\"errorCode\":\"0000\",\"msg\":\"nickName参数缺失\",\"data\":\" \"}";
        String token=request.getHeader("token");
        if (token==null || token.length()==0)
            return "{\"success\":\"false\",\"errorCode\":\"0000\",\"msg\":\"token丢失\",\"data\":\" \"}";
        User u = null;
        try {
            u=(User)redisUtils.get(token);
        }catch (Exception e){
            throw new RuntimeException("Redis值损坏，无法转换成User类型");
        }
        u.setNickName(user.getNickName() == null || user.getNickName().length() > 0 ? u.getNickName() : user.getNickName());
        u.setSignature(user.getSignature());
        u.setTelephone(user.getTelephone() == null || user.getTelephone().length() > 0 ? u.getTelephone() : user.getTelephone());
        if (userFeign.updateUser(user)) {
            //获取修改成功后的用户信息
            u = userFeign.findUserById(user.getUserId());
            //存放如rides中
            //ValueOperations<String, User> users = redisTemplate.opsForValue();
            redisUtils.set(token, user);
            //更新redis中的数据
            redisUtils.update(token,u);
            //返回修改后的用户信息
            return DtoUtil.returnSuccess("修改成功", u);
        } else {//修改失败
            return DtoUtil.returnFail("系统异常", "0000");
        }

    }



}
